import 'package:dio/dio.dart';
import 'package:enjoy_plus_hm/utils/event_bus.dart';
import 'package:enjoy_plus_hm/utils/http.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  Map userInfo = {"avatar": null, "nickName": null};
  final TextEditingController _nickNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _nickNameController.text = userInfo['nickName'] ?? '';
    });
  }

  /// 修改昵称
  editNickname() async {
    String nickName = _nickNameController.text;
    if (nickName.isEmpty) {
      return ToastUtil.showError('请输入昵称');
    }
    if (nickName.length > 5) {
      return ToastUtil.showError('昵称长度不能超过5个字符');
    }
    try {
      await http.put('/userInfo', data: {"nickName": nickName});
      ToastUtil.showSuccess('修改成功');
    } catch (e) {
      ToastUtil.showError('修改失败');
    }
  }

  ///  显示底部弹窗
  showBottomSheet() async {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(10),
          height: 180,
          child: Column(
            children: [
              ListTile(
                title: Text('拍照'),
                leading: Icon(Icons.camera_alt),
                trailing: Icon(Icons.arrow_forward_ios_rounded),
                onTap: () async {
                  final ImagePicker picker = ImagePicker();
                  final XFile? photo = await picker.pickImage(
                    source: ImageSource.camera,
                  );
                  if (photo != null) {
                    uploadAvatar(photo.path);
                  }
                },
              ),
              ListTile(
                title: Text('相册'),
                leading: Icon(Icons.image),
                trailing: Icon(Icons.arrow_forward_ios_rounded),
                onTap: () async {
                  final ImagePicker picker = ImagePicker();
                  final XFile? image = await picker.pickImage(
                    source: ImageSource.gallery,
                  );
                  if (image != null) {
                    uploadAvatar(image.path);
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

  /// 上传头像
  uploadAvatar(String imagePath) async {
    try {
      // 1. 构建一个表单对象formData。接收一个Map<String, dynamic>并将这个Map中的键值对自动转换成FormData支持的格式
      FormData formData = FormData.fromMap({
        "file":
            kIsWeb
                ? MultipartFile.fromBytes(
                  await XFile(imagePath).readAsBytes(),
                  filename: 'avatar.jpg',
                  contentType: DioMediaType('image', 'jpeg'),
                ) // 支持h5端
                : MultipartFile.fromFileSync(imagePath), // 通过本地路径创建文件对象(支持app端)
        "type": 'avatar',
      });
      // 2. 发请求
      final res = await http.post('/upload', data: formData);
      if (res['code'] != 10000) return ToastUtil.showError('上传图片失败');
      setState(() {
        userInfo['avatar'] = res['data']['url'];
      });
      ToastUtil.showSuccess('上传图片成功');
    } catch (e) {
      ToastUtil.showError('上传图片失败$e');
    } finally {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
        // 自定义导航栏左侧控件
        leading: IconButton(
          onPressed: () {
            eventBus.fire(RefreshMine());
            Navigator.pop(context);
          },
          icon: const Icon(Icons.arrow_back),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        showBottomSheet();
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child:
                            userInfo['avatar'] == null
                                ? Image.asset(
                                  'assets/images/avatar_1.jpg',
                                  width: 40,
                                  height: 40,
                                )
                                : Image.network(
                                  userInfo['avatar'],
                                  width: 40,
                                  height: 40,
                                ),
                      ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12),
                  ],
                ),
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  onChanged: (value) {
                    setState(() {
                      userInfo['nickName'] = value;
                    });
                  },
                  onEditingComplete: () {
                    editNickname();
                  },
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12),
            ],
          ),
        ],
      ),
    );
  }
}
